package cc.magicjson.easy.batch.application.service;

import cc.magicjson.easy.batch.application.domain.User;
import cc.magicjson.easy.batch.config.BatchSqlProvider;
import cc.magicjson.easy.batch.core.BatchProcessor;
import cc.magicjson.easy.batch.model.BatchResult;
import cc.magicjson.easy.batch.template.SqlTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserBatchService {
    private final BatchProcessor<User> batchProcessor;
    private final BatchSqlProvider sqlProvider;





    public BatchResult<User> batchInsertUsers(List<User> users) {
        return batchProcessor.builder()
            .items(users)
            .sqlKey("user.batchInsert")
            .parameterExtractor(user -> new Object[]{user.getName(), user.getEmail()})
            .batchSize(1000)
            .withProgress((progress, affected) ->
                log.info("Progress: {}%, Affected: {}", progress, affected))
            .withRetry(3, 1000)
            .parallel(4)
            .execute();
    }

    public BatchResult<User> batchUpdateUsers(List<User> users) {
        SqlTemplate template = sqlProvider.getTemplate("user.update")
            .setTableInfo("users", new String[]{"email","name"})
            .setUpdateClause(new String[]{"email","name"})
            .setWhereClause("id = ?");

        return batchProcessor.builder()
            .items(users)
            .sqlTemplate(template)
            .parameterExtractor(user -> new Object[]{user.getEmail(), user.getName()})
            .allowPartialSuccess()
            .execute();
    }
}
